import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xiongan_app_yy/common/user_singleton.dart';
import 'package:xiongan_app_yy/entrys/rp/inv_counter_details_entity.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';
import 'package:xiongan_app_yy/pages/common/LoadBuilder.dart';
import 'package:xiongan_app_yy/pages/common/TextFieldItem.dart';
import 'package:xiongan_app_yy/provider/into_warehousing_provider.dart';
import 'package:xiongan_app_yy/provider/inv_counter_info.dart';
import 'package:xiongan_app_yy/utils/image_utils.dart';
import 'package:xiongan_app_yy/utils/toast_utils.dart';
import 'package:xiongan_app_yy/widgets/comm/CustomDialog.dart';
import 'package:xiongan_app_yy/widgets/comm/left_icon_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/number_count_button.dart';

class InvCounterDetails extends StatefulWidget {
  final Map<dynamic, dynamic> args;
  @override
  _InvCounterDetailsState createState() => _InvCounterDetailsState();

  InvCounterDetails(this.args);
}

class _InvCounterDetailsState extends State<InvCounterDetails> {
  InvCounterDetailsEntity bean;
  List<InvCounterDetailsData> exhibitionList;
  Color bgColor = Colors.white;
  @override
  void initState() {
    print("11111111111111111111111111111111111111111");
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      Provider.of<CounterInfo>(context).getData(widget.args["id"]);
      print("22222222222222222222222222222222222222");
    });
  }

  @override
  Widget build(BuildContext context) {
    print("3333333333333333333333");
    exhibitionList = Provider.of<CounterInfo>(context).data;
    return Scaffold(
      appBar: new AppBar(
        leading: LeftIconWidget(icon: Icons.chevron_left, isize: 36),
        backgroundColor: Color(0XFF00A5F1),
        title: Text(
          "清点与贴标",
          style: TextStyle(fontSize: 18),
        ),
        elevation: 0,
        centerTitle: true,
      ),
      body: LoadBuilder(
          visibility: Provider.of<CounterInfo>(context).netStatus1,
          bgColor: bgColor,
          builder: Column(
            children: <Widget>[
              Expanded(
                  child: RefreshIndicator(
                child: ListView.builder(
                    itemBuilder: (BuildContext context, int index) {
                      return InvCounterDetailsItem(index, exhibitionList);
                    },
                    itemCount: exhibitionList.length),
                onRefresh: _refresh,
              )),
              Container(
                width: double.infinity,
                height: 48,
                color: Color(0xff00A5F1),
                child: FlatButton(
                    onPressed: () {
                      oneKeySubmission();
                    },
                    child: Text(
                      "一键提交",
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    )),
              )
            ],
          )),
    );
  }

  Future<void> _refresh() async {
    await Future.delayed(Duration(seconds: 1), () {
      return null;
    });
    Provider.of<CounterInfo>(context).setNetStatus1=true;
    Provider.of<CounterInfo>(context).getData(widget.args["id"]);
  }

/*  void getData() {
    InternetAPI.getInstance().get("WMS/MiWarehouseInOrder/GetCheckMaterialList",
            (data) {
      print(data);
       bean=InvCounterDetailsEntity.fromJson(data);
       Provider.of<CounterInfo>(context).setBean(bean.datas);
       //exhibitionList=bean.datas;
       setState(() {
            load=false;
          });
        }, params: {
          'orderid': widget.args["id"],
          'operaterUserId': DataSingleton().Data.id,
          'userId': DataSingleton().Data.id,
          'tenantId': DataSingleton().Data.tenantId,
          'warehouseid': DataSingleton().warehouseChoice.id,
          'pageNo': -1
        });
  }*/

  void oneKeySubmission() {
    setState(() {
      bgColor = Colors.black26;
    });
    Provider.of<CounterInfo>(context).setNetStatus1=true;
    List<Map<String, dynamic>> submissioList = new List();
    for (int i = 0; i < exhibitionList.length; i++) {
      if (exhibitionList.elementAt(i).ischeck == false) {
        submissioList.add(exhibitionList.elementAt(i).toJson());
      }
    }
    InternetAPI.getInstance().post("WMS/MiWarehouseInOrder/SubmissionCheck",
        (value) {
      if (value == true) {
        /* TostUtil.showToast("清点成功");
       Navigator.pop(context);*/

        showDialog(context:context,barrierDismissible:true,builder: (context){
          return  CustomDialog(
            title: "清点成功",
            content: "是否去交接",
            outsideDismiss: false,
            confirmCallback: () {
              Navigator.pushNamed(
                  context, '/into_handover_details',
                  arguments: widget.args);
            },
            dismissCallback: () {
              Provider.of<IntoWareHousingProvider>(context).getList();
              Navigator.pop(context);
            },
          );
        } );


      }
      Provider.of<CounterInfo>(context).setNetStatus1=false;
    }, errorCallBack: (err) {
          Provider.of<CounterInfo>(context).setNetStatus1=false;
    }, params: {
      'orderid': widget.args["id"],
      'operaterUserId': DataSingleton().Data.id,
      'userId': DataSingleton().Data.id,
      'tenantId': DataSingleton().Data.tenantId,
      'warehouseid': DataSingleton().warehouseChoice.id,
      'inCheckList': submissioList
    });
  }
}

class InvCounterDetailsItem extends StatefulWidget {
  final int index;
  final List<InvCounterDetailsData> exhibitionList;

  @override
  _InvCounterDetailsItemState createState() => _InvCounterDetailsItemState();

  InvCounterDetailsItem(this.index, this.exhibitionList);
}

class _InvCounterDetailsItemState extends State<InvCounterDetailsItem> {
  final TextEditingController controller0 = TextEditingController();
  final TextEditingController controller1 = TextEditingController();
  InvCounterDetailsData data;
  Widget imageWidget;
  String image = "assets/images/build.png";

  @override
  void initState() {
    data = widget.exhibitionList.elementAt(widget.index);
    if (data.realquantity == null) {
      controller0.text = data.quantity.toInt().toString();
    } else {
      controller0.text = data.realquantity.toInt().toString();
    }
    controller1.text = data.batchno;
    if (data.imageurl != null && image == "assets/images/build.png") {
      ImageDownloadUtil.getImageBase64(data.imageurl, (data) {
      if(mounted){
        setState(() {
          image = data;
        });
      }
      });
    }

  }

  @override
  Widget build(BuildContext context) {
    //data = Provider.of<CounterInfo>(context).data.elementAt(widget.index);
    if (data.inOrderDetailSnList.length > 0) {
      controller0.text = data.inOrderDetailSnList.length.toString();
      data.quantity = data.inOrderDetailSnList.length;
    }
    imageWidget = ImageDownloadUtil.isImageType(image);

    return Container(
      margin: EdgeInsets.only(top: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: ConstrainedBox(
              constraints:
                  BoxConstraints.expand(width: double.infinity, height: 144),
              child: Stack(
                children: <Widget>[
                  Positioned(
                    width: 144,
                    height: 144,
                    child: imageWidget,
                  ),
                  Positioned(
                    child: Text(
                      "名称:${data.materialname}",
                      style: TextStyle(
                        color: Color(0xff323232),
                        fontSize: 14,
                      ),
                    ),
                    left: 152,
                  ),
                  Positioned(
                    child: Text(
                      "物资编码:${data.materialcode}",
                      style: TextStyle(
                        color: Color(0xff323232),
                        fontSize: 14,
                      ),
                    ),
                    left: 152,
                    top: 24,
                  ),
                  Positioned(
                    child: Text(
                      "型号:${data.model??""}",
                      style: TextStyle(
                        color: Color(0xff323232),
                        fontSize: 14,
                      ),
                    ),
                    left: 152,
                    top: 48,
                  ),
                  Positioned(
                    child: Text(
                      "规格:${data.spec??""}",
                      style: TextStyle(
                        color: Color(0xff323232),
                        fontSize: 14,
                      ),
                    ),
                    left: 152,
                    bottom: 48,
                  ),
                  Positioned(
                    child: Text(
                      "单位:${data.baseunitname}",
                      style: TextStyle(
                        color: Color(0xff323232),
                        fontSize: 14,
                      ),
                    ),
                    left: 152,
                    bottom: 24,
                  ),
                  Positioned(
                    child: Text(
                      "计划入库数:${data.quantityAPP.toInt()}",
                      style: TextStyle(
                        color: Color(0xff323232),
                        fontSize: 14,
                      ),
                    ),
                    left: 152,
                    bottom: 0,
                  ),
                ],
              ),
            ),
          ),
          Container(
            color: Colors.white,
            margin: EdgeInsets.only(top: 10),
            padding: EdgeInsets.only(top: 10, bottom: 10, left: 16, right: 16),
            child: Column(
              children: <Widget>[
                /* TextFieldItem(
                    textEditingController: controller0, hintText: "实际入库数"),*/
                NumbercCountButton(
                  height: 50,
                  buttonWidth: 50,
                  textEditingController: controller0,
                  maxNumber: data.quantityAPP.toInt(),
                  hintText: "输入实际拣选数",
                  onChangedFuns: (value) {
                    print("值$value");
                    if (data.inOrderDetailSnList.length == 0) {
                      data.quantity = int.parse(controller0.text);
                    } else if (data.inOrderDetailSnList.length == 1 &&
                        data.inOrderDetailSnList
                                .elementAt(0)
                                .materialsnid
                                .toString() ==
                            "") {
                      data.quantity = int.parse(controller0.text);
                    } else {
                      data.quantity = data.inOrderDetailSnList.length;
                    }
                    print(data.quantity);
                  },
                ),
                TextFieldItem(
                  textEditingController: controller1,
                  hintText: "批次",
                  onChangedFuns: (value) {
                    data.batchno = controller1.text;
                  },
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                        child: FlatButton(
                            color: Color(0xffeeeeee),
                            onPressed: () {
                              Navigator.pushNamed(context, "/invCounterId",
                                  arguments: {
                                    "index": widget.index,
                                    "data": data
                                  });
                            },
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(6)),
                            child: Text(
                              "已录入${data.inOrderDetailSnList.length}个实物ID",
                              style: TextStyle(
                                  color: Color(0xff646464), fontSize: 16),
                            ))),
                    Container(
                      width: 10,
                    ),
                    FlatButton(
                        color: Colors.blue,
                        disabledColor: Color(0xFFF5BD36),
                        onPressed: data.ischeck
                            ? null
                            : () {
                                submission();
                              },
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(6)),
                        child: Text(
                          data.ischeck ? "已提交" : "提交",
                          style: TextStyle(color: Colors.white, fontSize: 16),
                        ))
                  ],
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  void submission() {
    Provider.of<CounterInfo>(context).setNetStatus1=true;
    print("提交数据");
    print(data.toJson().toString());
    data.batchno = controller1.text;
    if (data.inOrderDetailSnList.length == 0) {
      data.quantity = int.parse(controller0.text);
    } else if (data.inOrderDetailSnList.length == 1 &&
        data.inOrderDetailSnList.elementAt(0).materialsnid.toString() == "") {
      data.quantity = int.parse(controller0.text);
    } else {
      data.quantity = data.inOrderDetailSnList.length;
    }
    InternetAPI.getInstance()
        .post("WMS/MiWarehouseInOrder/AddMiWarehouseInCheck", (value) {
      if (value == true) {
        TostUtil.showToast("清点成功");
        setState(() {
          data.ischeck = true;
        });
        Provider.of<CounterInfo>(context).setNetStatus1=false;
      }
    }, params: data.toJson());
  }

 /* @override
  void dispose() {
    image=null;
  }*/

}
